##
##	Mercurial-analyzer
##
## Todo: skriv om...

from xml.dom import minidom
import logger

## Parses a dom file
def parsedom(file):
	try:
		dom = minidom.parse(file)
	except Exception:
	  logger.printerror("Failed to parse the xml file " + file);
	  exit()

	return dom


class Project:
	name="-noname-"
	type="svn"
	urls = []

def getprojects (file = 'settings/projects.xml'):
	projects = [];
	dom = parsedom(file)
	logger.printinfo("Parsing project-settings")
	try:
		for node in dom.getElementsByTagName('project'):
			proj = Project();
			tmp = [];
			for xnode in node.getElementsByTagName("name"):
				proj.name = xnode.firstChild.wholeText
			for xnode in node.getElementsByTagName("type"):
				proj.type = xnode.firstChild.wholeText
			for xnode in node.getElementsByTagName("url"):
				tmp.append(xnode.firstChild.wholeText);
	
			proj.urls = tmp;
			projects.append(proj);
	except Exception:
		  logger.printerror("Malformed xml elements")
		  exit()

	return projects;


class DbSettings:
	host=""
	username=""
	password=""
	schema=""

def getdbsettings  (file = 'settings/db.xml'):
	logger.printinfo("Parsing database-settings")
	dom = parsedom(file)
	dbsetting = DbSettings()

	try:
		for node in dom.getElementsByTagName('database'):
			for xnode in node.getElementsByTagName("host"):
				dbsetting.host = xnode.firstChild.wholeText
			for xnode in node.getElementsByTagName("username"):
				dbsetting.username = xnode.firstChild.wholeText
			for xnode in node.getElementsByTagName("password"):
				dbsetting.password = xnode.firstChild.wholeText
			for xnode in node.getElementsByTagName("schema"):
				dbsetting.schema = xnode.firstChild.wholeText
	except Exception:
		  logger.printerror("Malformed xml elements")
		  exit()

	# Validate, or atleast check that variables have been changed...
	if(dbsetting.host==""):
		  logger.printerror("Missing host")
		  exit()

	if(dbsetting.username==""):
		  logger.printerror("Missing username")
		  exit()

	if(dbsetting.password==""):
		  logger.printerror("Missing password")
		  exit()

	if(dbsetting.schema==""):
		  logger.printerror("Missing schema")
		  exit()

	return dbsetting;


class Type:
	name="-noname-"
	changelog=""
	regex=""
	checkout=""

def gettypes (file = 'settings/types.xml'):
	types = {};
	dom = parsedom(file)
	logger.printinfo("Parsing supported vcs info")
	try:
		for node in dom.getElementsByTagName('type'):
			proj = Type();
			for xnode in node.getElementsByTagName("name"):
				proj.name = xnode.firstChild.wholeText
			for xnode in node.getElementsByTagName("changelog"):
				proj.changelog = xnode.firstChild.wholeText
			for xnode in node.getElementsByTagName("regex"):
				proj.regex = xnode.firstChild.wholeText
			for xnode in node.getElementsByTagName("checkout"):
				proj.checkout = xnode.firstChild.wholeText
		
			types[proj.name]=proj;
	except Exception:
		  logger.printerror("Malformed xml elements")
		  exit()

	return types;
